<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%category}}".
 *
 * @property string $id
 * @property string $pid
 * @property string $name
 * @property string $sort
 * @property string $title
 * @property string $keywords
 * @property string $description
 * @property string $image
 * @property string $create_time
 * @property integer $status
 */
class Category extends \yii\db\ActiveRecord
{
	public $top;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%category}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['pid', 'sort', 'create_time', 'status'], 'integer'],
            [['name'], 'required'],
            [['name'], 'string', 'max' => 40],
            [['title', 'keywords'], 'string', 'max' => 100],
            [['description'], 'string', 'max' => 200],
            [['image'], 'string', 'max' => 80],
			[['sort', 'create_time', 'pid'], 'default' , 'value' => function ($model, $attribute) {
				switch ($attribute) {
					case 'sort':
						$return = 10;
						break;
					case 'create_time':
						$return = time();
						break;
					default:
						$return = 0;
				}
				return $return;
			}],
			[['sort'], 'filter', 'filter' => function ($value) {
				return abs($value);
			}],
			[['image'], 'file', 'extensions' => 'jpg, png, gif, jpeg', 'mimeTypes' => 'image/jpg, image/png, image/gif, image/jpeg']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'pid' => '上级分类',
            'name' => '分类名称',
            'sort' => '排序',
            'title' => 'SEO标题',
            'keywords' => 'SEO关键字',
            'description' => 'SEO描述',
            'image' => '封面图片',
            'create_time' => '创建时间',
            'status' => '态状',
        ];
    }

	/**
	 * 获取分类的名称
	 * @param int $id 分类id
	 * @return string
	 */
	public function getPname($id){
		return $this->findOne($id)->name;
	}

	public function getCateList($id = 0){
		if ($id === 0) {
			$list = $this->find()->select(['id', 'name'])->all();
		}else{
			$list = $this->find()->select(['id', 'name'])->where('id != ' . $id)->all();
		}
		return $list;
	}
}
